
var crypto = require('crypto');
var fs = require('fs');
var request = require('request');

function genFileMD5(file) {
    var buffer = fs.readFileSync(file);
    var fsHash = crypto.createHash('md5');
    fsHash.update(buffer);
    return fsHash.digest('hex');
}

function genStringMD5(str = "") {
    var hash = crypto.createHash('md5');
    hash.update(new Buffer.from(str.toString()));
    return hash.digest('hex');
}


function genRequestFileMD5(url) {
    return new Promise(function (resolve, reject) {
        var options = {
            'method': 'GET',
            'url': url,
            'headers': {
            }
        };
        request(options, function (error, response) {
            if (error) throw new Error(error);
            //console.log(response.body);
            let buffer = response.body;
            var fsHash = crypto.createHash('md5');
            fsHash.update(buffer);
            resolve(fsHash.digest('hex'));
        });

    })
}

function wxDecryptData(sessionKey, encryptedData, iv) {
    let crypto = require('crypto');
    // base64 decode
    var sessionKey = new Buffer(sessionKey, 'base64')
    encryptedData = new Buffer(encryptedData, 'base64')
    iv = new Buffer(iv, 'base64')

    try {
        // 解密
        var decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv)
        // 设置自动 padding 为 true，删除填充补位
        decipher.setAutoPadding(true)
        var decoded = decipher.update(encryptedData, 'binary', 'utf8')
        decoded += decipher.final('utf8')

        decoded = JSON.parse(decoded)

    } catch (err) {
        throw err.message
    }

    if (decoded.watermark.appid !== 'wx0ad38ba00d298c15') {
        throw new Error('Illegal Buffer')
    }

    return decoded
}


module.exports = {
    genFileMD5,
    genStringMD5, wxDecryptData,
    genRequestFileMD5:genRequestFileMD5,
    MD5:genStringMD5
}